package com.vincent.seeyou.nfc;

import android.app.Activity;
import android.content.Intent;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.NfcEvent;
import android.os.Parcelable;
import android.widget.Toast;

import java.nio.charset.Charset;

import cn.bmob.im.BmobUserManager;

/**
 * Created by Vincent on 2014/9/3.
 */
public class SYNFCManager {

    private final String mimeType = "application/com.vincent.seeyou";
    private final String applicationRecord = "com.vincent.seeyou";


    public static SYNFCManager synfcManager = null;

    public static SYNFCManager getInstance(){
        if (synfcManager == null) {
            synfcManager = new SYNFCManager();
        }
        return synfcManager;
    }
    public SYNFCManager() {}


    public void  initPushMessage(final Activity activity,final String payload) {
        NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(activity);
        if (nfcAdapter != null) {
            nfcAdapter.setNdefPushMessageCallback(new NfcAdapter.CreateNdefMessageCallback() {
                @Override
                public NdefMessage createNdefMessage(NfcEvent nfcEvent) {
                    NdefMessage message = createMessage(payload);
                    return message;
                }
            },activity);
        }
    }

    public String handlerIntent(Intent intent){
        String payload = "";
        Parcelable[] messages = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
        if(messages!=null){
            NdefMessage message = (NdefMessage)messages[0];
            NdefRecord record = message.getRecords()[0];
            payload = new String(record.getPayload());
        }
        return payload;
    }

    private NdefMessage createMessage( String payload ){
        byte[] mimeByte = mimeType.getBytes(Charset.forName("US-ASCII"));
        NdefMessage nfcMessage = new NdefMessage(new NdefRecord[]{
                new NdefRecord(NdefRecord.TNF_MIME_MEDIA, mimeByte, new byte[0], payload.getBytes()), NdefRecord.createApplicationRecord(applicationRecord)
        });
        return nfcMessage;
    }


}
